

SControllers.controller('flowcrawl_ctrl', ['$scope', '$http', '$timeout',
  function($scope, $http, $timeout) {

    var carouselDefaults = {
        interval: false,
        pause: 'hover',
        wrap: false
    }
    
    $scope.flowcrawl_plugins = [];
    $scope.edit_flowcrawl_plugin = {'steps':[]};
    $scope._current_step = {};

    $scope.baction_overlap_id = "";
    function newBAction(isoverlap) {
        var id = Math.uuid(8, 16);
        var overlap = true;
        if ( !(typeof(isoverlap) === "boolean" && isoverlap) ) {
            $scope.baction_overlap_id = id;
            overlap = false;
        }
        if ($scope.baction_overlap_id === "")
            $scope.baction_overlap_id = id;
        return {"action":"click", "css":"", "tvalue":"", "kvalue":"","sleepTime":"100", "repTimes":"1", "ismultiple":true, "intoKeyword":false, "overlap":overlap, "id":id, "oid":$scope.baction_overlap_id};
    }
    $scope._current_baction = newBAction();

    var history_carousel_stepid = -1;

    $scope.bactionModel = [{
        id:1,
        type :'click',
    }, {
        id:2,
        type :'scroll',
    }, {
        id:3,
        type :'sendkey',
    }, {
        id:4,
        type :'type',
    }];

    $scope.nextStepTypeModel = [{
        id:1,
        type :'click',
    }, {
        id:2,
        type :'href-attribute',
    }];

    $('.carousel').carousel('pause');
    $('.carousel').carousel(carouselDefaults);

    $scope.find_crawl_name = "";
    $scope.current_crawl = undefined;
    $scope.crawl_list = [];

    function checkLoadDisplay() {
        if ($scope.current_crawl !== undefined) {
            if ($scope.current_crawl["isLoad"]) {
                $("#load").hide();
                $("#unload").show();
                $("#todetail").show();
            } else {
                $("#load").show();
                $("#unload").hide();
                $("#todetail").hide();
            }
        }
    }

    $scope.load_crawl_list = function(pageno, perpage) {
        var url = "/spiderkit/flowcrawl_list?pageno="+pageno+"&perpage="+perpage;

        $http.get(url).success(
            function(data) {
                $scope.crawl_list = data;
                if (data.length > 0) {
                    var has = false;
                    if ($scope.current_crawl !== undefined) {
                        for(var i = 0; i < $scope.crawl_list.length; i ++) {
                            if ($scope.crawl_list[i]['name'] === $scope.current_crawl['name']) {
                                $scope.current_crawl = $scope.crawl_list[i];
                                has = true;
                            }
                        }
                    }
                    if (!has) {
                        $scope.current_crawl = data[0];
                    }
                } else {
                    $scope.current_crawl = undefined;
                }
                checkLoadDisplay();
            }
        );
    };

    $scope.on_crawl_list_init = function(id) {
        if (id === $scope.current_crawl._id.$oid){
            $timeout(function() {$("#"+id).addClass("list-group-item-info");}, 10); 
        }
    };

    $scope.find_crawl = function() {
        if ($scope.find_crawl_name === undefined || $scope.find_crawl_name === "")
            return;

        var url = "/spiderkit/flowcrawl_info?pluginName=" + $scope.find_crawl_name;

        $http.get(url).success(
            function(data) {
                if (data["steps"] === undefined){
                    showMessage("没找到 " + $scope.find_crawl_name);
                } else {
                    $scope.current_crawl = data;
                }
                checkLoadDisplay();
            }
        );
    };

    $scope.on_crawl_list_click = function(target) {
        for (var i = 0; i < $scope.crawl_list.length; i ++) {
            $("#"+$scope.crawl_list[i]._id.$oid).removeClass("list-group-item-info");
            if ($scope.crawl_list[i]._id.$oid === target.id) {
                $("#"+target.id).addClass("list-group-item-info");
                $scope.current_crawl = $scope.crawl_list[i];
                checkLoadDisplay();
            }
        }
    };
    
    $scope.on_list_pages_setting_type = function(target) {
        var cdata = target.getAttribute("cdata");
        var sdata = target.getAttribute("sdata");
        var pdata = target.getAttribute("pdata");

        $scope._current_step["nextPagesSettingType"] = target.parentNode.getAttribute("data-type");

        $(".pages-setting-"+sdata).removeClass("active");
        $(".pages-types-item-"+sdata).hide();
        $(pdata).addClass("active");
        $(cdata).show();
    };
    
    $scope.show_step_desc = function(stepid, desc) {
        var id = "#grumble-" + stepid;
        $(id).grumble({
            text: "1",
            angle: 225,
            distance: 0,
            showAfter: 100,
            type: 'alt-',
            hideAfter: 1000
        });
    }

    $scope.hide_step_desc = function(stepid) {
        var id = "#grumble-" + stepid;
    }

    function resume_carousel_nav() {
        $("#carousel-nav-li-"+(history_carousel_stepid+1).toString()).removeClass("active");
        history_carousel_stepid = -1;
        $("#carousel-nav-li-"+(history_carousel_stepid+1).toString()).addClass("active");
        $("#step-info-box").hide();
    }

    $scope.edit_crawl = function() {
        $scope.edit_flowcrawl_plugin = $scope.current_crawl;
        $scope._current_baction = newBAction();

        $('#crawl-info-panel')[0].style.display = "none";
        $('#carousel-create-flowcrawl')[0].style.display = "block";
        $('.carousel-first-active:first').addClass('active');
        $('#crawl-name-disabled').show();
        $('#crawl-name').hide();

        resume_carousel_nav();
        checkFirstDisplay();

        $("#show-extract-config").hide();
        $scope.safeApply();
    }

    $scope.load_crawl = function() {
        var pluginName = $scope.current_crawl["name"];
        var url = "/spiderkit/flowcrawl_load?pluginName=" + pluginName;

        $http.get(url).success(
            function(data) {
                $("#load").hide();
                $("#unload").show();
                $("#todetail").show();
                $scope.load_crawl_list(1, 100);
            }
        );
    };

    $scope.unload_crawl = function() {
        $("#unloadCrawlNameModal").modal();
    }

    $scope.do_unload_crawl = function() {
        var pluginName = $scope.current_crawl["name"];
        var url = "/spiderkit/flowcrawl_unload?pluginName=" + pluginName;

        $http.get(url).success(
            function(data) {
                $scope.load_crawl_list(1, 100);
            }
        );

        var url = "/spiderkit/plugin_manager?action=delete&pluginName="+pluginName;
        $http.get(url).success(
            function(data) {
                $("#load").show();
                $("#unload").hide();
                $("#todetail").hide();
            }
        );
    };

    $scope.reload_crawl = function() {
        var pluginName = $scope.current_crawl["name"];
        var url = "/spiderkit/plugin_manager?action=delete&pluginName="+pluginName;
        $http.get(url).success(
            function(data) {
                var url = "/spiderkit/flowcrawl_load?pluginName=" + pluginName;
                $http.get(url).success(
                    function(data) {
                        $("#load").hide();
                        $("#unload").show();
                        $("#todetail").show();
                        $scope.load_crawl_list(1, 100);
                    }
                );
            }
        );
    }
    $scope.remove_crawl = function() {
        $("#removeCrawlNameModal").modal();
    }

    $scope.do_remove_crawl = function() {
        if ($scope.current_crawl === undefined) {
            return;
        }

        if ($scope.current_crawl["name"] === undefined && $scope.current_crawl["name"] === "") {
            return;
        }

        $scope.do_unload_crawl();

        var url = "/spiderkit/flowcrawl_remove"+"?pluginName="+$scope.current_crawl["name"];

        $http.get(url).success(
            function(data) {
                if (data) {
                    showMessage("删除成功！");
                } else {
                    showMessage("删除失败！");
                }
                $scope.load_crawl_list(1, 100);
            }
        );
    }

    $scope.carousel_prev = function() {
        $('.carousel').carousel('prev');
        $('.carousel').carousel('pause');
        $("#extract-config").hide();
        $scope.load_extract_config();
    };

    $scope.carousel_next = function() {
        $('.carousel').carousel('next');
        $('.carousel').carousel('pause');
        $("#extract-config").hide();
        $scope.load_extract_config();
    };

    $scope.create_crawl = function() {
        $scope.edit_flowcrawl_plugin = {'steps':[], 'isLoad':false};
        $scope.baction_overlap_id = "";

        $('#crawl-info-panel')[0].style.display = "none";
        $('#carousel-create-flowcrawl')[0].style.display = "block";
        $('.carousel-first-active:first').addClass('active');
        $('#crawl-name-disabled').hide();
        $('#crawl-name').show();

        resume_carousel_nav();
        checkFirstDisplay();
    };
    
    var applyTimer;
    $scope.safeApply = function(fn) {
        var phase = $scope.$root.$$phase;
        if (phase == '$apply' || phase == '$digest') {
            applyTimer = $timeout(function() {$scope.safeApply(fn)}, 5);
        } else {
            $scope.$apply();
            if (typeof (fn) === "function") {
                fn();
            }
        }
    }

    function check_step_form() {
        if ($scope._current_step["waitCssList"] === undefined || $scope._current_step["waitCssList"] === "") {
            return false;
        }

        if ($scope._current_step["pageType"] === "2") {
            if ($scope._current_step["startUrls"] === undefined || $scope._current_step["startUrls"] === "") {
                return false;
            }
        }

        if ($scope._current_step["pageType"] !== "0") {
            if ($scope._current_step["nextStepCss"] === undefined || $scope._current_step["nextStepCss"] === "") {
                return false;
            }
        }

        if ($scope._current_step["nextStepType"] === undefined) {
            return false;
        }

        if ($scope._current_step["nextStepType"] === "href-attribute") {
            if ($scope._current_step["nextStepHrefAttribute"] === undefined || $scope._current_step["nextStepHrefAttribute"] === "") {
                return false;
            }
        }

        if ($scope._current_step["pageType"] === "1" || $scope._current_step["isListPage"] === true) {
            if ($scope._current_step["currentPageCss"] === undefined) {
                return false;
            }
            if($scope._current_step["nextPagesSettingType"] === "1") {
                if ($scope._current_step["nextPageCss"] === undefined) {
                    return false;
                }
                if ($scope._current_step["nextPageType"] === undefined) {
                    return false;
                }
                if ($scope._current_step["nextPageHrefAttribute"] === undefined) {
                    return false;
                }
            } else if($scope._current_step["nextPagesSettingType"] === "0") {
                if ($scope._current_step["pageCountStartWith"] === undefined) {
                    return false;
                }
                if ($scope._current_step["pageCountCss"] === undefined) {
                    return false;
                }
            }
        }

        return true;
    }

    var message_modal_show = false;
    $('#messageModal').on('show.bs.modal', function (e) {
        message_modal_show = true;
    });

    $('#messageModal').on('hide.bs.modal', function (e) {
        message_modal_show = false;
    });

    function showMessage(text) {
        $('#message').html(text);
        if (!message_modal_show) {
            $('#messageModal').modal({keyboard: false});
        }
    }

    function checkFlowcrawlPluginName(name) {
        if (name === undefined || name === "") {
            showMessage("名称不能为空");
            return false;
        }

        var re =new RegExp("^[a-zA-Z][a-zA-Z0-9_]{3,30}$"); 
        if (!re.test(name)) {
            showMessage("名称不符合规则，名称必须以字母开头，允许3-30字节，允许字母数字下划线！");
            return;
        }
        return true;
    }

    $scope.on_baction_tvalue_change = function() {
        var action = $scope._current_baction["action"];
        var tvalue = $scope._current_baction["tvalue"];
        if (action === "type" && tvalue !== undefined && tvalue !== "") {
            $("#intoKeyword-"+$scope._current_step["stepID"]).show();
        } else {
            $("#intoKeyword-"+$scope._current_step["stepID"]).hide();
            $scope._current_baction["intoKeyword"] == false;
        }
    }

    $scope.on_baction_change = function() {
        var action = $scope._current_baction["action"];
        var tvalue = $scope._current_baction["tvalue"];
        if (action === "type" && tvalue !== undefined && tvalue !== "") {
            $("#intoKeyword-"+$scope._current_step["stepID"]).show();
        } else {
            $("#intoKeyword-"+$scope._current_step["stepID"]).hide();
            $scope._current_baction["intoKeyword"] == false;
        }
    }

    $scope.add_baction = function(target) {
        var stepid = target.getAttribute("data");
//        var kvalue = $("#baction-key-value-"+stepid)[0].value;
//        $scope._current_baction["kvalue"] = kvalue;
        if ($scope._current_baction["css"] === "") {
            return;
        }
        if ($scope._current_baction["action"] === "sendkey" && $scope._current_baction["kvalue"] === "" ) {
            return;
        }
        if ($scope._current_baction["action"] === "type" && $scope._current_baction["tvalue"] === "" ) {
            return;
        }

        if ($scope._current_step["baction"] === undefined) {
            $scope._current_step["baction"] = [];
        }

        $scope._current_step["baction"].push($scope._current_baction);

        var overlap = $scope._current_baction["overlap"];
        if (typeof(overlap) === "boolean" && overlap)
            $scope._current_baction = newBAction(true);
        else
            $scope._current_baction = newBAction(false);
    };

    $scope.edit_baction_ok = function() {
        $scope._current_baction = newBAction();
        $("#edit-baction-ok-"+$scope._current_step["stepID"]).hide();
        $("#add-baction-"+$scope._current_step["stepID"]).show();
    }

    $scope.edit_baction = function(id) {
        for ( var i = 0; i < $scope._current_step["baction"].length; i ++) {
            if ($scope._current_step["baction"][i]["id"] === id) {
                $("#edit-baction-ok-"+$scope._current_step["stepID"]).show();
                $("#add-baction-"+$scope._current_step["stepID"]).hide();
                $scope._current_baction = $scope._current_step["baction"][i];

                var action = $scope._current_baction["action"];
                var tvalue = $scope._current_baction["tvalue"];
                if (action === "type" && tvalue !== undefined && tvalue !== "") {
                    $("#intoKeyword-"+$scope._current_step["stepID"]).show();
                } else {
                    $("#intoKeyword-"+$scope._current_step["stepID"]).hide();
                    $scope._current_baction["intoKeyword"] == false;
                }
                return;
            }
        }
    };

    $scope.delete_baction = function(target) {
        var id = target.id;
        for ( var i = 0; i < $scope._current_step["baction"].length; i ++) {
            if ($scope._current_step["baction"][i]["id"] === id) {
                $scope._current_step["baction"].splice(i, 1);
                return;
            }
        }
    };
    
    $scope.create_crawl_step = function() {
        
        var stepCount = $scope.edit_flowcrawl_plugin['steps'].length+1;

        if (stepCount > 1 && !check_step_form()) {
            showMessage("配置数据不合法！");
            return;
        } else if (stepCount === 1 && !checkFlowcrawlPluginName($scope.edit_flowcrawl_plugin["name"])) {
            return;
        }

        $scope._current_baction = newBAction();
        $scope._current_step["complete"] = true;
        $scope._current_step["isLast"] = false;

        var current_step = {"stepID": stepCount.toString(), "group": "DynamicIp", "isListPage":false, "useIncrementalFilter":false, "nextStepHrefAttribute": "href", "nextPageHrefAttribute": "href", "complete":false, "isLast":true, "method":"config", "baction":[], "needCarryCookie":true, "nextStepOpenNewPage":false, "carryCookieName":"*"};

        if (stepCount === 1) {
            current_step["pageType"] = "2";
        } else {
            current_step["pageType"] = "3";
        }

        $scope.edit_flowcrawl_plugin['steps'].push(current_step);

        $scope._current_step = current_step;
        $scope._current_step["nextStepType"] = "href-attribute";
        $scope._current_step["nextPageType"] = "href-attribute";
        $scope._current_step["nextPageASync"] = true;
        $scope._current_step["nextPageClickWaitTime"] = "5";
        $scope._current_baction = newBAction();

        $scope.safeApply( function() {
            $scope.carousel_next();
            checkDisplay();
        });
    };

    $('.carousel').on('slide.bs.carousel', function (val) {

        $scope._current_baction = newBAction();
        $scope.baction_overlap_id = "";
        if (val["relatedTarget"] === undefined || val["relatedTarget"].id === undefined || val["relatedTarget"].id === "") {
            $scope._current_step = {};
            checkFirstDisplay();

            $("#carousel-nav-li-0").addClass("active");
            $("#carousel-nav-li-"+(history_carousel_stepid+1).toString()).removeClass("active");
            $("#step-info-box").hide();
            $("#show-extract-config").hide();
            history_carousel_stepid = -1;
            return;
        }

        var id = parseInt(val["relatedTarget"].id)-1;

        if (id > $scope.edit_flowcrawl_plugin['steps'].length) {
            return;
        }

        $("#step-info-box").show();

        $("#extract-config").hide();
        $scope.load_extract_config();
        $scope.on_carousel_step_change(id);

        $("#edit-baction-ok-"+$scope._current_step["stepID"]).hide();
        $("#add-baction-"+$scope._current_step["stepID"]).show();
    });

    $scope.on_carousel_step_change = function(id) {

        if (typeof(id) === "string")
            id = parseInt(id)-1;

        if (history_carousel_stepid !== -1 && (id+1).toString() === $scope._current_step["stepID"])
            return;

        $("#carousel-nav-li-"+(id+1).toString()).addClass("active");
        $("#carousel-nav-li-"+(history_carousel_stepid+1).toString()).removeClass("active");
        history_carousel_stepid = id;

        if (id < 0)
            return;

        $scope._current_step = $scope.edit_flowcrawl_plugin['steps'][id];

        if ($scope._current_step["pageType"] === "1" || $scope._current_step["isListPage"] === true) {
            $(".pages-setting-"+$scope._current_step["stepID"]).removeClass("active");
            $(".pages-types-item-"+$scope._current_step["stepID"]).hide();
        }

        checkDisplay();

        $('.carousel').carousel('pause');
    }

    $scope.change_step_page = function(id) {
        $scope._current_step = $scope.edit_flowcrawl_plugin['steps'][id];
    };

    var oldCrawlName = "";
    var oldCrawlDesc = "";
    $scope.copy_crawl = function() {
        oldCrawlName = $scope.current_crawl['name'];
        oldCrawlDesc = $scope.current_crawl['desc'];
        $("#copyCrawlNameModal").modal({backdrop: 'static', keyboard: false});
    };

    $scope.cancel_copy_crawl = function() {
        $scope.current_crawl['name'] = oldCrawlName;
        $scope.current_crawl['desc'] = oldCrawlDesc;
        oldCrawlName = "";
        oldCrawlDesc = "";
    };

    $scope.do_copy_crawl = function() {
        if ($scope.current_crawl["name"] === oldCrawlName) {
            showMessage("名称不能相同");
            $scope.cancel_copy_crawl();
            return;
        }

        if (!checkFlowcrawlPluginName($scope.current_crawl["name"])) {
            $scope.cancel_copy_crawl();
            return;
        }

        $scope.current_crawl["isLoad"] = false;

        var crawlInfo = encodeURIComponent(angular.toJson($scope.current_crawl));
        var url = "/spiderkit/flowcrawl_copy"+"?oldName="+oldCrawlName+"&newName="+$scope.current_crawl['name']+"&crawlInfo="+crawlInfo;
        console.log("oldCrawlName " + oldCrawlName);

        $http.get(url).success(
            function(data) {
                showMessage("复制成功！");
                $scope.show_crawl_info();
                $scope._current_step = {};
                oldCrawlName = "";
                oldCrawlDesc = "";
            }
        ).error(
            function() {
                $scope.cancel_copy_crawl();
                showMessage("复制失败！");
                oldCrawlName = "";
                oldCrawlDesc = "";
            }
        );
    };

    $scope.save_crawl = function() {

        var stepCount = $scope.edit_flowcrawl_plugin['steps'].length+1;
        if (stepCount > 1 && !check_step_form()) {
            showMessage("配置数据不合法！");
            return;
        }
        
        if (!checkFlowcrawlPluginName($scope.edit_flowcrawl_plugin["name"]))
            return;

        var url = "/spiderkit/get_plugin_info?pluginName="+$scope.edit_flowcrawl_plugin["name"];
        $http.get(url).success(
            function(data) {
                var plugin_info = data[0];
                if (plugin_info["isLocalPlugin"] === undefined) {
                    $scope.do_save_crawl();
                    return;
                }

                if (plugin_info["isLocalPlugin"]) {
                    for (var i = 0; i < plugin_info["plugins"].length ; i ++) {
                        var info = plugin_info["plugins"][i];
                        if (info["processable"]) {
                            if (info["isProcessing"] || info["isLaunched"]) {
                                $("#saveCrawlNameModal").modal();
                                return;
                            }
                        }
                    }
                    $scope.do_save_crawl();
                }
            }
        );
    };

    $scope.do_save_crawl = function() {
        var crawlInfo = encodeURIComponent(angular.toJson($scope.edit_flowcrawl_plugin));
        var url = "/spiderkit/flowcrawl_add"+"?pluginName="+$scope.edit_flowcrawl_plugin['name']+"&crawlInfo="+crawlInfo;

        $http.get(url).success(
            function(data) {
                if ($scope.edit_flowcrawl_plugin["isLoad"]) {
                    $scope.current_crawl = $scope.edit_flowcrawl_plugin;
                    $scope.reload_crawl();
                }
                showMessage("保存成功！");
                $scope.show_crawl_info();
                $scope.edit_flowcrawl_plugin = {'steps':[]};
                $scope._current_step = {};
            }
        );
    };

    $scope.on_page_type_change = function() {
        checkDisplay();
    };

    $scope.on_carry_cookie_checkbox_change = function() {
        checkDisplay();
    };

    function checkDisplay() {
        $("#intoKeyword-"+$scope._current_step["stepID"]).hide();
        if ($scope._current_step["pageType"] !== "0") {
            if ($scope._current_step["nextStepType"] !== undefined) {
                if ($scope._current_step["nextStepType"] === "href-attribute") {
                    $(".next-step-href-attr-"+$scope._current_step["stepID"])[0].style.display = "block";
                    $(".nsonp-"+$scope._current_step["stepID"])[0].style.display = "none";
                } else {
                    $(".next-step-href-attr-"+$scope._current_step["stepID"])[0].style.display = "none";
                    $(".nsonp-"+$scope._current_step["stepID"])[0].style.display = "block";
                }
            }
        }

        if ($scope._current_step["needCarryCookie"] === false) {
            $("#carrycookie-"+$scope._current_step["stepID"])[0].style.display = "none";
        } else {
            $("#carrycookie-"+$scope._current_step["stepID"])[0].style.display = "block";
        }

        if ($scope._current_step["pageType"] === "2") {
            $(".start-step-"+$scope._current_step["stepID"])[0].style.display = "block";
        } else {
            $(".start-step-"+$scope._current_step["stepID"])[0].style.display = "none";
        }

        if ($scope._current_step["pageType"] === "0") {
            $(".end-step-"+$scope._current_step["stepID"])[0].style.display = "block";
            $(".add-new-step-"+$scope._current_step["stepID"])[0].style.display = "none";
            $(".next-step-css-"+$scope._current_step["stepID"])[0].style.display = "none";
            $(".next-step-href-attr-"+$scope._current_step["stepID"])[0].style.display = "none";
            $(".next-step-type-"+$scope._current_step["stepID"])[0].style.display = "none";
            $("#islistpage-"+$scope._current_step["stepID"])[0].style.display = "none";
        } else {
            $(".end-step-"+$scope._current_step["stepID"])[0].style.display = "none";
            $(".add-new-step-"+$scope._current_step["stepID"])[0].style.display = "block";
            $(".next-step-css-"+$scope._current_step["stepID"])[0].style.display = "block";
            $(".next-step-href-attr-"+$scope._current_step["stepID"])[0].style.display = "block";
            $(".next-step-type-"+$scope._current_step["stepID"])[0].style.display = "block";
            $("#islistpage-"+$scope._current_step["stepID"])[0].style.display = "block";
        }
        
        if (!$scope._current_step["isLast"]) {
            $(".complete-step-"+$scope._current_step["stepID"])[0].style.display = "block";
            $(".add-new-step-"+$scope._current_step["stepID"])[0].style.display = "none";
        } else {
            $(".complete-step-"+$scope._current_step["stepID"])[0].style.display = "none";
            $(".add-new-step-"+$scope._current_step["stepID"])[0].style.display = "block";
        }

        if ($scope._current_step["pageType"] === "1" || $scope._current_step["isListPage"] === true) {
            $(".listpage-next-"+$scope._current_step["stepID"]).show();
            setListPageSetting();
        } else {
            $(".listpage-next-"+$scope._current_step["stepID"]).hide();
        }

        $('.carousel').carousel('pause');
    };

    function setListPageSetting() {
        if($scope._current_step["nextPagesSettingType"] === undefined) {
            var firste = $(".pages-setting-"+$scope._current_step["stepID"]+":first");
            firste.addClass("active");
            $scope._current_step["nextPagesSettingType"] = firste[0].getAttribute("data-type");
            $(firste[0].firstChild.getAttribute("cdata")).show();
        } else {
            var es = $(".pages-setting-"+$scope._current_step["stepID"]);
            for (var i = 0; i < es.length; i ++) {
                if (es[i].getAttribute("data-type") === $scope._current_step["nextPagesSettingType"]) {
                    es[i].setAttribute("class", es[i].getAttribute("class")+" active");
                    if (es[i].firstChild !== undefined) {
                        $(es[i].firstChild.getAttribute("cdata")).show();
                    }
                    break;
                }
            }
        }
        if ($scope._current_step["nextPageType"] === "href-attribute") {
            $("#next-page-click-async-or-sync-"+$scope._current_step["stepID"]).hide();
            $("#next-page-href-attribute-"+$scope._current_step["stepID"]).show();
        } else {
            $("#next-page-click-async-or-sync-"+$scope._current_step["stepID"]).show();
            $("#next-page-href-attribute-"+$scope._current_step["stepID"]).hide();
        }
    }

    function checkFirstDisplay() {
        if ($scope.edit_flowcrawl_plugin["steps"].length <= 0) {
            $(".first-add-step")[0].style.display = "block";
            $(".first-next-step")[0].style.display = "none";
        } else {
            $(".first-add-step")[0].style.display = "none";
            $(".first-next-step")[0].style.display = "block";
        }
        $("#extract-config").hide();
        $('.carousel').carousel('pause');
    }

    $scope.on_nextstep_type_change = function() {
        checkDisplay();
        if ($scope._current_step["nextStepType"] === "click")
            $scope._current_step["useIncrementalFilter"] = false;
    };

    $scope.print_info = function() {
        console.log(JSON.stringify($scope.edit_flowcrawl_plugin));
        console.log(JSON.stringify($scope._current_step));
    };

    $scope.show_crawl_info = function() {
        $('#crawl-info-panel')[0].style.display = "block";
        $('#carousel-create-flowcrawl')[0].style.display = "none";
        $scope.load_crawl_list(1, 100);
    };
    
    $scope.on_next_page_type_change = function() {
        checkDisplay();
        if ($scope._current_step["nextPageType"] === "click")
            $scope._current_step["useIncrementalFilter"] = false;
    }
    
    $scope.load_crawl_list(1, 100);
    
    // --------- extract config part ------

    $scope.dataTypes = [{
        id:1,
        type :'text',
    }, {
        id:2,
        type :'html',
    }, {
        id:3,
        type :'image',
    }, {
        id:4,
        type :'script',
    }];
    
    $scope.keysModel = WebKitKeys;

    var default_script = "function parse(source) {\n\n}";

    $scope.current_field = {"id":Math.uuid(8, 16), "datatype":"text", "isindex":false, "ismultiple":false};
    $scope.config = {};
    var has_extract_config = false;

    function createJavaScriptEditor(scriptCode) {
        var node = document.getElementById("jsEditor");
        var js_code_mirror = CodeMirror(node, {
            value: scriptCode,
            lineNumbers : false,
            mode : "javascript"
        });
        js_code_mirror.setSize(760, 600);
        return js_code_mirror;
    }

    var jsEditor = createJavaScriptEditor(default_script);

    showXPathEditor();

    $scope.on_use_data_mq_change = function() {
        if ($scope.config["dataPushToMQ"]) {
            $("#dataMQName").show();
        } else {
            $("#dataMQName").hide();
        }
    };

    $scope.hide_extract_config = function() {
        $("#extract-config").hide(200, function(){
            $("#show-extract-config").show();
        });
    };

    $scope.show_extract_config = function() {
        $scope.load_extract_config();
        $("#extract-config").show(200);
        $("#show-extract-config").hide();
        //$scope.on_use_data_mq_change();
    };

    var script_editor_modal_show = false;
    $('#jsEditorModal').on('show.bs.modal', function (e) {
        script_editor_modal_show = true;
    });

    $('#jsEditorModal').on('hide.bs.modal', function (e) {
        script_editor_modal_show = false;
    });
    
    function showJsEditorModal() {
        if (!script_editor_modal_show)
            $('#jsEditorModal').modal({backdrop: 'static', keyboard: false});
    }
    
    $scope.open_jseditor = function() {
        if ($scope.current_field['script'] === undefined || $scope.current_field['script'] === "") {
            $scope.current_field['script'] = default_script;
        }
        jsEditor.getDoc().setValue($scope.current_field['script']);
        showJsEditorModal();
    };

    $scope.on_extract_datatype_change = function() {
        if ($scope.current_field['datatype'] === "script") {
            showJSEditor();
        } else {
            if ($scope.current_field['datatype'] === "text") {
                $("#isindex_checkbox").show();
            } else {
                $scope.current_field["isindex"] = false;
                $("#isindex_checkbox").hide();
            }
            showXPathEditor();
        }
    };

    $scope.save_js_script = function() {
        $scope.current_field['script'] = jsEditor.getDoc().getValue();
    };

    $scope.load_extract_config = function(target) {

        if ($scope._current_step['stepID'] === undefined) {
            $("#show-extract-config").hide();
            return;
        }

        $("#show-extract-config").show();

        showAddField();

        var url = "/spiderkit/flowcrawl_extract_get?pluginName="+$scope.edit_flowcrawl_plugin['name']+"&stepID="+$scope._current_step['stepID'];
        $http.get(url).success(
            function(data){
                if (data.length === 0) {
                    $scope.config = {"name":$scope.edit_flowcrawl_plugin['name'], "stepID":$scope._current_step['stepID'], "fields":[]};
                    extract_task_save_view();
                    $("#test-extract-button").hide(); 
                    has_extract_config = false;
                } else {
                    $scope.config = data[0];
                    $("#test-extract-button").show(); 
                    if (!$scope.config["isExtracting"]) {
                        extract_task_start_view();
                    } else {
                        extract_task_stop_view();
                    }
                    has_extract_config = true;
                }
                $("#index").hide();
                $("#step").hide();
            }
        );
    };


      function showJSEditor() {
          $("#editXPath").hide();
          $("#openJsEditor").show();
      }

      function showXPathEditor() {
          $("#editXPath").show();
          $("#openJsEditor").hide();
      }
      
      $scope.add_not_analyzed_mapping_field = function() {
          var field_name = $scope.current_field["key"];
          if (field_name === undefined || field_name === "")
              return;
          var url = "/spiderkit/flowcrawl_extract_add_not_analyzed_mapping_field?fieldName="+field_name;
          console.log(url);

          $http.get(url).success(
            function(data) {
                showMessage(data);
            }
          );
      };
      
      $scope.on_isindex_change = function() {
          console.log("on isindex change : " + $scope.current_field["isindex"]);
          if ($scope.current_field["isindex"] === true) {
              $("#add-not-analyzed-btn").show();
          } else {
              $("#add-not-analyzed-btn").hide();
          }
      };

      $scope.add_field = function() {
          $scope.config["fields"].push($scope.current_field);
          $scope.current_field = {"id":Math.uuid(8, 16), "datatype":"text", "isindex":false, "ismultiple":false};
          showXPathEditor();
          showAddField();
      };

      $scope.fix_field = function() {
          $scope.current_field = {"id":Math.uuid(8, 16), "datatype":"text", "isindex":false, "ismultiple":false};
          showXPathEditor();
          showAddField();
      };

      function showAddField() {
          $("#add-field-btn").show();
          $("#fix-field-btn").hide();
          $("#add-not-analyzed-btn").hide();
      }

      function showFixField() {
          $("#add-field-btn").hide();
          $("#fix-field-btn").show();
      }
      
      $scope.load_field = function(field) {
          $scope.current_field = field;
          if (field["datatype"] === "script") {
              showJSEditor();
          } else {
              showXPathEditor();
          }

          showFixField();

          if ($scope.current_field['datatype'] === "text") {
              $("#isindex_checkbox").show();
          } else {
              $scope.current_field["isindex"] = false;
              $("#isindex_checkbox").hide();
          }

          if ($scope.current_field["isindex"] === true) {
              $("#add-not-analyzed-btn").show();
          } else {
              $("#add-not-analyzed-btn").hide();
          }
      }
       
      $scope.delete_field = function(target) {
        var id = target.id;
        for ( var i = 0; i < $scope.config["fields"].length; i ++) {
            if ($scope.config["fields"][i]["id"] === id) {
                $scope.config["fields"].splice(i, 1);
                return;
            }
        }
      };
      
      $scope.save_config = function() {
          var configstr = encodeURIComponent(angular.toJson($scope.config));
          var url = "/spiderkit/flowcrawl_extract_save?pluginName="+$scope.edit_flowcrawl_plugin['name']+"&stepID="+$scope._current_step['stepID']+"&config="+configstr;
          showTimeoutTip($("#save-requesting-tips")[0]); 
          $http.get(url).success(
            function(data) {
                if (data === "success") {
                    showTimeoutTip($("#save-success-tips")[0]); 
                } else {
                    showTimeoutTip($("#save-failed-tips")[0]); 
                }
            }
          );
      };

      function ExtractorData() {
          this.tree = [];
      }

      function ExtractorTreeData() {
          this.text = "";
          this.selectable = false;
      }

      function createExtractorTreeData(obj) {
          var data = new ExtractorData();
          for (var p in obj) {
              data.tree.push(createExtractorTreeDataChildes(obj[p], p));
          }
          return data;
      }

      function createExtractorTreeDataChildes(fobj, prop) {
          var fields = [];
          var root = new ExtractorTreeData(); 
          root.text = prop;
          root.showcon = false;
          if (typeof(fobj) == "object") {
              for (var p in fobj) {
                  fields.push(createExtractorTreeDataChildes(fobj[p], p));
              }
              root.nodes = fields;
          } else {
              var leaf = new ExtractorTreeData(); 
              if (typeof (fobj) === "string") {
                  var re = new RegExp("^[a-zA-z]+://[^\s]*","g");
                  if (re.test(fobj)) {
                      fobj = "<a href=\""+fobj+"\">"+fobj+"</a>";
                  } else {
                      fobj = fobj.replace("\n","<br/>");
                      fobj = fobj.replace("\t","&nbsp;&nbsp;&nbsp;&nbsp;");
                      fobj = fobj.replace(" ","&nbsp;");
                  }
              }
              leaf.text = "<div style=\"width:750px; display:inline;\"><span style=\"table-layout:fixed; word-break:break-all; overflow:hidden;\">"+fobj+"</span></div>";
              leaf.selectable = false;
              fields.push(leaf);
              root.nodes = fields;
          }
          return root; 
      }

      function extract_task_start_view() {
          $("#extract-button").show();
          $("#i-extract-button").show();
          $("#extract-filter-button").show();
          $("#save-extract-button").show();
          $("#stop-extracting-button").hide();
          
        if ($scope._current_step["pageType"] === "0")
            $("#extract-doindex-button").show();
        else
            $("#extract-doindex-button").hide();
      }

      function extract_task_save_view() {
          $("#extract-button").hide();
          $("#i-extract-button").hide();
          $("#extract-filter-button").hide();
          $("#extract-doindex-button").hide();
          $("#save-extract-button").show();
          $("#stop-extracting-button").hide();
      }

      function extract_task_stop_view() {
          $("#extract-button").hide();
          $("#i-extract-button").hide();
          $("#extract-filter-button").hide();
          $("#extract-doindex-button").hide();
          $("#save-extract-button").hide();
          $("#stop-extracting-button").show();
      }

      function showStartTest() {
          $('#on-test-start').show();
          $('#on-test-error').hide();
          $('#on-test-info').hide();
          $('#extractTreeView').hide();
      }

      function showErrorTest() {
          $('#on-test-error').show();
          $('#on-test-start').hide();
          $('#on-test-info').hide();
          $('#extractTreeView').hide();
      }

      function showTestTree() {
          $('#on-test-error').hide();
          $('#on-test-start').hide();
          $('#on-test-info').hide();
          $('#extractTreeView').show();
      }

      function showTestInfo(content) {
          $('#on-test-error').hide();
          $('#on-test-start').hide();
          $('#extractTreeView').hide();
          $('#on-test-info')[0].innerHTML = content;
          $('#on-test-info').show();
      }

      $scope.test_extract_data = function() {
          if (!has_extract_config)
              return;

          var url = "/spiderkit/flowcrawl_extract_ctrl?action=test&stepID="+$scope._current_step['stepID']+"&pluginName="+$scope.edit_flowcrawl_plugin['name'];
          showStartTest();
          $('#treeViewModal').modal({backdrop: 'static', keyboard: false});
          $http.get(url).success(
            function(data) {
                if (data['status'] === "1") {
                    showTestTree();
                    $('#extractTreeView').treeview({data: createExtractorTreeData(data['data']).tree, levels: 1, nodeIcon:''});
                } else if (data['status'] === "-11") {
                    showTestInfo(data["message"]);
                }
            }
          ).error(function(){
              showErrorTest();
          });
      }
      
      var tipIsShow = false;
      var tipTimer = undefined;
      $('#tipsEditorModal').on('hide.bs.modal', function (e) {
          tipIsShow = false;
      });

      function showTimeoutTip(node) {
          $('#tips-content')[0].innerHTML = node.innerHTML;
          if (tipIsShow) {
              if (tipTimer !== undefined)
                  tipTimer.stop();
          } else {
              $('#tipsEditorModal').modal({backdrop: 'static', keyboard: false});
          }
          tipTimer = $timeout(function() {$('#tipsEditorModal').modal("hide")}, 1000);
      }

      $scope.stop_extract_data = function() {
          if (!has_extract_config)
              return;
          var url = "/spiderkit/flowcrawl_extract_ctrl?action=stop&stepID="+$scope._current_step['stepID']+"&pluginName="+$scope.edit_flowcrawl_plugin['name'];
          showTimeoutTip($("#stoping-extract-tips")[0]) 
          $http.get(url).success(
            function(data) {
                extract_task_start_view();
                showTimeoutTip($("#stop-extract-succ-tips")[0]); 
            }
          ).error(
            function(data) {
                showTimeoutTip($("#stop-extract-fail-tips")[0]); 
            }
          );
      }

      $scope.extract_data = function(taskType) {
          if (!has_extract_config)
              return;

          if (typeof(taskType) !== "number")
              return;

          var url = "/spiderkit/flowcrawl_extract_ctrl?action=start&taskType="+taskType+"&stepID="+$scope._current_step['stepID']+"&pluginName="+$scope.edit_flowcrawl_plugin['name'];
          showTimeoutTip($("#extract-requesting-tips")[0]); 
          $http.get(url).success(
            function(data) {
                if (data === "0") {
                    extract_task_stop_view();
                    showTimeoutTip($("#extract-success-tips")[0]); 
                } else if (data === "-1") {
                    showTimeoutTip($("#extract-running-tips")[0]); 
                } else {
                    showTimeoutTip($("#extract-failed-tips")[0]); 
                }
            }
          );
      }
  }]
);

function inputKeypressKey(e) {
    if (e.keyCode !== 0) {
        e.target.value = e.keyCode.toString();
    } else {
        e.target.value = e.charCode.toString();
    }
    return false;
}

